package org.mca.mcaweb.listener;

import java.io.Serializable;

import javax.enterprise.event.Observes;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.inject.Inject;

import org.jboss.seam.faces.event.qualifier.After;
import org.jboss.seam.faces.event.qualifier.RestoreView;
import org.mca.mcaweb.bean.LoggedUser;
import org.mca.mcaweb.bean.LoginBean;

import com.sun.org.apache.bcel.internal.generic.LOR;

public class LoginPhaseListener implements Serializable {

	private static final long serialVersionUID = 8940355465626905786L;

	private @Inject FacesContext context;
	private @Inject LoginBean loginBean;
	private @Inject LoggedUser loggedUser;
	private @Inject NavigationHandler handler;
	
	public void autoriza(@Observes @After @RestoreView PhaseEvent event ){
		
		
		if (!loginBean.isLoggedUser()) {
			if ("/pages/login.xhtml".equals(context.getViewRoot().getViewId())) {
				return;
			}
			handler.handleNavigation(context, null, "/pages/login?faces-redirect=true");
			context.renderResponse();

		} else {
			if (loggedUser.getEmpr() != null) {
				if (loggedUser.getEmpr().getEmprcodigo() == null) {
					if ("/pages/empresa.xhtml".equals(context.getViewRoot().getViewId())) {
						return;
					}
					handler.handleNavigation(context, null, "/pages/empresa?faces-redirect=true");
					context.renderResponse();
				} else {
					String[] url = context.getViewRoot().getViewId().split("\\.");
					url = url[0].split("/");
					String page = url[url.length - 1];
					// String directory = url[url.length-2];

					if ("login".equals(page) || "empresa".equals(page) || "edit".equals(page)	|| "view".equals(page)) {
						handler.handleNavigation(context, null,	"/pages/index?faces-redirect=true");
						context.renderResponse();
					}
				}
			}
		}
	}

	public LoggedUser getLoggedUser() {
		return loggedUser;
	}

	public void setLoggedUser(LoggedUser loggedUser) {
		this.loggedUser = loggedUser;
	}
	
}
